import json
import smtplib
import time
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

import requests


def sendEmail(text):
    mail_host = 'smtp.163.com'
    mail_user = 'leefengme'
    mail_pass = 'ZHNYRICPUNCRAMHO'
    sender = 'leefengme@163.com'
    receivers = ['leefengme@163.com']
    message = MIMEMultipart('related')
    message.attach(MIMEText(f'<h3>{text}</h3>', 'html', 'utf-8'))
    message['Subject'] = '天津摇号结果查询'
    message['From'] = sender
    # 接受方信息
    message['To'] = receivers[0]
    try:
        smtpObj = smtplib.SMTP()
        # 连接到服务器
        smtpObj.connect(mail_host, 25)
        # 登录到服务器
        smtpObj.login(mail_user, mail_pass)
        # 发送
        smtpObj.sendmail(
            sender, receivers, message.as_string())
        # 退出
        smtpObj.quit()
        print('success')
    except smtplib.SMTPException as e:
        print('error', e)


cookies = {
    '_trs_uv': 'lfroq5et_3499_bqbi',
}

headers = {
    'Accept': 'application/json, text/plain, */*',
    'Accept-Language': 'zh-CN,zh;q=0.9',
    'Connection': 'keep-alive',
    'Content-Type': 'application/json;charset=UTF-8',
    # 'Cookie': '_trs_uv=lfroq5et_3499_bqbi',
    'Origin': 'https://xkctk.jtys.tj.gov.cn',
    'Referer': 'https://xkctk.jtys.tj.gov.cn/web/common/personNorm',
    'Sec-Fetch-Dest': 'empty',
    'Sec-Fetch-Mode': 'cors',
    'Sec-Fetch-Site': 'same-origin',
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) '
                  'Chrome/113.0.0.0 Safari/537.36',
    'sec-ch-ua': '"Google Chrome";v="113", "Chromium";v="113", "Not-A.Brand";v="24"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"macOS"',
}
if __name__ == '__main__':
    now = time.strftime("%Y%m", time.localtime())
    json_data = {
        'issueNumber': now,
        'applyCode': '0138103321284',
        'pageNo': 1,
        'pageSize': 15,
    }
    try:
        response = requests.post(
            'https://xkctk.jtys.tj.gov.cn/front/common/query/person/norm',
            cookies=cookies,
            headers=headers,
            json=json_data,
        )
        result = response.text
        jsonObj = json.loads(result)
        if jsonObj['code'] == 200:
            if jsonObj['data']['totalCount'] == 0:
                sendEmail(f"{now} 本期未中")
            else:
                sendEmail(f"{now} 中签了🎉🎉🎉")
        else:
            sendEmail(f"{now} 请求失败{result}")
    except Exception as e:
        print(e)
        sendEmail(f"请求错误{e}")
